﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XChip_Common
{
  public  class AppHelper
    {

        //定义key地址
        private static uint keyBin = 0xfcfff021;
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static uint XorNotEncryption(string str)
        {
            uint temp = 0;
            uint data = Convert.ToUInt32(str, 16);
            temp = data ^ keyBin;
            return ~temp;
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static uint XorNotDecryption(string str)
        {
            uint temp = 0;
            uint data = Convert.ToUInt32(str, 16);
            temp = (~data) ^ keyBin;
            return temp;
        }
        /// <summary>
        /// 字符串转UTF8
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StringToUTF8(string str)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            string hex = BitConverter.ToString(bytes).Replace("-", "");
            return hex;
        }
        /// <summary>
        /// UTF8转字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string HexStringToString(string hex)
        {
            // 每两个字符表示一个字节，所以我们需要确保hex字符串长度是偶数  
            if (hex.Length % 2 != 0)
            {
                throw new ArgumentException("请输入正确的十六进制数据");
            }

            // 将hex字符串转换为字节数组  
            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < hex.Length; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            }

            // 使用Encoding类将字节数组转换为字符串  
            return Encoding.UTF8.GetString(bytes); // 或者使用 Encoding.ASCII 如果它是ASCII编码的  
        }
        ///  <summary>
        ///  依据连接串名字connectionName返回数据连接字符串
        ///  </summary>
        ///  <param name="connectionName"></param>
        ///  <returns></returns>
        public static string GetConnectionStringsConfig(string connectionName)
        {
            string connectionString =
                    ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
            Console.WriteLine(connectionString);
            return connectionString;
        }

        ///  <summary>
        ///  更新连接字符串
        ///  </summary>
        ///  <param name="newName">  连接字符串名称  </param>
        ///  <param name="newConString">  连接字符串内容  </param>
        ///  <param name="newProviderName">  数据提供程序名称  </param>
        public static void UpdateConnectionStringsConfig(string newName,
            string newConString,
            string newProviderName)
        {
            bool isModified = false;    //  记录该连接串是否已经存在
                                        //  如果要更改的连接串已经存在
            if (ConfigurationManager.ConnectionStrings[newName] != null)
            {
                isModified = true;
            }
            //  新建一个连接字符串实例
            ConnectionStringSettings mySettings =
                new ConnectionStringSettings(newName, newConString, newProviderName);
            //  打开可执行的配置文件*.exe.config
            Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //  如果连接串已存在，首先删除它
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            //  将新的连接串添加到配置文件中.
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            //  保存对配置文件所作的更改
            config.Save(ConfigurationSaveMode.Modified);
            //  强制重新载入配置文件的ConnectionStrings配置节
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }


        ///  <summary>
        ///  返回＊.exe.config文件中appSettings配置节的value项
        ///  </summary>
        ///  <param name="strKey"></param>
        ///  <returns></returns>
        public static string GetAppConfig(string strKey)
        {
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == strKey)
                {
                    return ConfigurationManager.AppSettings[strKey];
                }
            }
            return null;
        }

        ///  <summary>
        ///  在＊.exe.config文件中appSettings配置节增加一对键、值对
        ///  </summary>
        ///  <param name="newKey"></param>
        ///  <param name="newValue"></param>
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            bool isModified = false;
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == newKey)
                {
                    isModified = true;
                }
            }

            // Open App.Config of executable
            Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // You need to remove the old settings object before you can replace it
            if (isModified)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            // Add an Application Setting.
            config.AppSettings.Settings.Add(newKey, newValue);
            // Save the changes in App.config file.
            config.Save(ConfigurationSaveMode.Modified);
            // Force a reload of a changed section.
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }


        /// <summary>
        /// 清理文件
        /// </summary>
        /// <param name="v"></param>
        /// <param name="isbool"></param>
        public static void ClearFileToPath(string v, bool isbool)
        {
            //setShowMsg($"清理文件---》》》》开始");

            DirectoryInfo folder = new DirectoryInfo(v);
            foreach (DirectoryInfo file in folder.GetDirectories())
            {
                if (isbool)
                {
                    if (DateTime.Compare(file.CreationTime, DateTime.Now.AddDays(-7)) < 0 && file.FullName.Contains($"Bin{DateTime.Now.AddDays(-7).ToString("yyyyMM")}"))
                    {
                        Directory.Delete(file.FullName, true);
                    }
                }
                else
                {
                    if (file.FullName.Contains($"Bin{DateTime.Now.ToString("yyyy")}"))
                    {
                        Directory.Delete(file.FullName, true);
                    }
                }

            }

            var pathList = GenerateFileHelp.GetFileTimePath(v, "*.txt");
            var pathList2 = GenerateFileHelp.GetFileTimePath(v, "*.bin");
            foreach (KeyValuePair<string, DateTime> item in pathList)
            {
                if (isbool)
                {
                    if (DateTime.Compare(item.Value, DateTime.Now.AddDays(-7)) < 0 && (item.Key.Contains(".txt")))
                    {
                        if (!item.Key.Contains("reset") && !item.Key.Contains("save_exit") && !item.Key.Contains("说明文档") && !item.Key.Contains("readme")) //需要过滤文件
                        {
                            File.Delete(item.Key);
                        }
                    }
                }
                else
                {


                    if (!item.Key.Contains("reset") && !item.Key.Contains("save_exit") && !item.Key.Contains("说明文档") && !item.Key.Contains("readme"))
                    {
                        File.Delete(item.Key);
                    }
                }

            }

            foreach (KeyValuePair<string, DateTime> item in pathList2)//删除安装目录下bin文件
            {
                if (isbool)
                {


                    if (DateTime.Compare(item.Value, DateTime.Now.AddDays(-7)) < 0)
                    {
                        File.Delete(item.Key);
                    }
                }
                else
                {
                    File.Delete(item.Key);
                }

            }
            // setShowMsg($"清理文件《《《《---结束");
        }



        public static string NameTypeToString(string str) {
            var strlast =   str.Substring(str.Length - 2, 2);
            String nameT = str;
            if (strlast.ToLower().Contains("_h")|| strlast.ToLower().Contains("_l"))
            {
                nameT = str.Substring(0, str.Length - 2);
            }
            else if (strlast.ToLower().Contains("m0")
                || strlast.ToLower().Contains("m1")
                || strlast.ToLower().Contains("m2")
                || strlast.ToLower().Contains("m3")
                || strlast.ToLower().Contains("m4")
                || strlast.ToLower().Contains("m5")
                || strlast.ToLower().Contains("m6")
                || strlast.ToLower().Contains("m7")
                || strlast.ToLower().Contains("en")
                )
            {
                nameT = str.Substring(0, str.Length - 3);
            }
            else if (str.ToLower().Contains("_long"))
            {
                nameT = str.ToLower().Replace("_long", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h") || strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            else if (str.ToLower().Contains("_short"))
            {
                nameT = str.ToLower().Replace("_short", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h")|| strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            else if (str.ToLower().Contains("_veryshort"))
            {
                nameT = str.ToLower().Replace("_veryshort", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h") || strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            else if (str.ToLower().Contains("_day"))
            {
                nameT = str.ToLower().Replace("_day", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h") || strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            else if (str.ToLower().Contains("_day_set"))
            {
                nameT = str.ToLower().Replace("_day_set", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h") || strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            else if (str.ToLower().Contains("_night"))
            {
                nameT = str.ToLower().Replace("_night", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h") || strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            else if (str.ToLower().Contains("_night_set"))
            {
                nameT = str.ToLower().Replace("_night_set", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h") || strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            else if (str.ToLower().Contains("_midnight"))
            {
                nameT = str.ToLower().Replace("_midnight", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h") || strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            else if (str.ToLower().Contains("_color"))
            {
                nameT = str.ToLower().Replace("_color", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h") || strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            else if (str.ToLower().Contains("_gray"))
            {
                nameT = str.ToLower().Replace("_gray", "");
                strlast = nameT.Substring(nameT.Length - 2, 2);
                if (strlast.ToLower().Contains("_h") || strlast.ToLower().Contains("_l"))
                {
                    nameT = nameT.Substring(0, nameT.Length - 2);
                }
            }
            return nameT.ToLower();
        }

    }
}
